#!/bin/bash

# IoT Cloud Platform Setup Script
# This script helps you get started with the IoT Cloud Platform

set -e

echo "🚀 IoT Cloud Platform Setup"
echo "================================"

# Check prerequisites
echo "📋 Checking prerequisites..."

# Check Go version
if ! command -v go &> /dev/null; then
    echo "❌ Go is not installed. Please install Go 1.21+"
    exit 1
fi

GO_VERSION=$(go version | awk '{print $3}' | sed 's/go//')
echo "✅ Go version: $GO_VERSION"

# Check Docker
if ! command -v docker &> /dev/null; then
    echo "❌ Docker is not installed. Please install Docker"
    exit 1
fi
echo "✅ Docker is available"

# Check Docker Compose
if ! command -v docker-compose &> /dev/null; then
    echo "❌ Docker Compose is not installed. Please install Docker Compose"
    exit 1
fi
echo "✅ Docker Compose is available"

echo ""
echo "🔧 Setting up the environment..."

# Create necessary directories
mkdir -p logs
mkdir -p data/postgres
mkdir -p data/redis
mkdir -p data/influxdb
mkdir -p data/kafka

# Download dependencies
echo "📦 Installing Go dependencies..."
go mod tidy

# Copy configuration file if it doesn't exist
if [ ! -f "config/config.local.yaml" ]; then
    echo "📝 Creating local configuration file..."
    cp config/config.yaml config/config.local.yaml
    echo "✅ Configuration file created at config/config.local.yaml"
    echo "📌 Please edit this file with your specific settings"
fi

echo ""
echo "🐳 Starting infrastructure services with Docker Compose..."

# Start infrastructure services
docker-compose up -d postgres redis influxdb kafka zookeeper emqx

echo "⏳ Waiting for services to be ready..."
sleep 30

# Check if services are running
echo "🔍 Checking service health..."

if docker-compose ps | grep -q "Up"; then
    echo "✅ Infrastructure services are running"
else
    echo "❌ Some services failed to start. Please check docker-compose logs"
    exit 1
fi

echo ""
echo "🏗️  Building the application..."

# Build the application
go build -o bin/iot-platform cmd/main.go

echo "✅ Application built successfully"

echo ""
echo "🎉 Setup completed successfully!"
echo ""
echo "📚 Next steps:"
echo "1. Edit config/config.local.yaml with your settings"
echo "2. Start the application: ./bin/iot-platform"
echo "3. Or run in development mode: go run cmd/main.go"
echo "4. Visit http://localhost:8080/health to verify"
echo ""
echo "📖 Documentation:"
echo "- API Documentation: http://localhost:8080/api/v1/docs"
echo "- EMQX Dashboard: http://localhost:18083 (admin/public)"
echo "- Grafana Dashboard: http://localhost:3000 (admin/admin)"
echo "- Prometheus: http://localhost:9090"
echo ""
echo "🔐 Default credentials:"
echo "- PostgreSQL: postgres/password"
echo "- EMQX: admin/public"
echo "- Grafana: admin/admin"
echo ""
echo "⚠️  Security notice: Please change default passwords in production!"
echo ""
echo "Happy coding! 🚀"